package it.infodea.tapestrydea.components;

import it.infodea.tapestrydea.services.pageinfo.PageInfoService;
import it.infodea.tapestrydea.services.pageinfo.bean.PageInfoBean;
import it.infodea.tapestrydea.support.annotations.PageInfo;
import it.infodea.tapestrydea.support.enumerations.SecurityGroup;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.tapestry5.annotations.IncludeStylesheet;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SetupRender;
import org.apache.tapestry5.ioc.annotations.Inject;

@IncludeStylesheet(value = "../assets/styles/tapestrydea.css")
public class PageInfoMenuDea {

	@Parameter(required = true)
	@Property
	private SecurityGroup securityGroup;

	@Parameter
	private boolean lowerLevelToo = false;

	@Inject
	private PageInfoService pageInfoService;

	@SuppressWarnings("unused")
	@Property(write = false)
	private Collection<String> categories;

	@Property(write = false)
	private List<PageInfoBean> infos;

	private String category;

	@SetupRender
	void initMenu() {
		categories = pageInfoService.getCategoriesByParent(PageInfo.CATEGORY_ROOT);
		setCategory(PageInfo.CATEGORY_ROOT);
	}

	public boolean isNotEmpty() {
		return !infos.isEmpty();
	}

	private List<PageInfoBean> getAllowedPagesInfo(PageInfoService service, String category) {
		List<PageInfoBean> result = new ArrayList<PageInfoBean>();
		for (PageInfoBean pageInfo : service.getPageInfoByCategory(category)) {
			if (!result.contains(pageInfo) && pageInfo.isNormalMode()) {
				if (PageInfo.CATEGORY_ROOT.equals(category) && pageInfo.getLink() == null) {
					continue;
				}
				if (canAccess(pageInfo)) {
					result.add(pageInfo);
				}
			}
		}
		return result;
	}

	private boolean canAccess(PageInfoBean pageInfoBean) {
		int userSecuritylevel = securityGroup.getLevel();
		int pageSecuritylevel = pageInfoBean.getPageSecuritylevel();
		return (lowerLevelToo) ? userSecuritylevel <= pageSecuritylevel : userSecuritylevel == pageSecuritylevel;
	}

	public String getCategory() {
		return category;
	}

	public void setCategory(String category) {
		this.category = category;
		infos = getAllowedPagesInfo(pageInfoService, category);
	}

}
